package com.dayuanit.dy17.mix.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestThreadBiz {

   private static final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5,
            5,
            60,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(5));

    public static void sleep() {
        try {
            Thread.sleep(1 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void pay() {
        System.out.println("pay()");
        sleep();
    }

    public static void sendEmail() {
        System.out.println("sendEmail()");
        sleep();
    }

    public static void sendMessage() {
        System.out.println("sendMessage()");
        sleep();
    }

    public static void riskmanger() {
        System.out.println("riskmanger()");
        sleep();
    }

    public static void dataBase() {
        System.out.println("dataBase()");
        sleep();
    }


    public static void main(String[] args) {
        //下个订单：1.支付订单成功后，可能要做一系列的事情：
        // 发邮件给商家，发短信通知客户支付成功，告诉风控系统订单信息，发送消息给数据中心做统计
        //记录日志(必须是所有步骤都结束后，才能输出日志)
        pay();

//        sendEmail();
//        sendMessage();
//        riskmanger();
//        dataBase();

        System.out.println("---------------");

        //通过线程池，将部分业务异步化，来提升程序的性能
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                sendEmail();
            }
        });

        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                sendMessage();
            }
        });

        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                riskmanger();
            }
        });

        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                dataBase();
            }
        });

        //此时无法保证上面4个任务全部结束了
        System.out.println("支付成功");

    }
}
